package com.study.www.config;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCursor;
import org.bson.Document;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.Field;
import java.util.List;

/**
 * @author : Administrator.zhuyanpeng
 * @date : 2019/10/28 - 10:37
 */
public class BeanUtils {

    private final static String MONGO_ID = "_id";

    public static <T> List<T> copyList(FindIterable<Document> sourceArray, Class<T> t) {
        List<T> list = Lists.newArrayList();
        MongoCursor<Document> iterator = sourceArray.iterator();
        while (iterator.hasNext()) {
            Document next = iterator.next();
            if (!ObjectUtils.isEmpty(next.get(MONGO_ID))) {
                next.put("id", next.get(MONGO_ID).toString());
            }
            String s = JSONObject.toJSONString(next);
            list.add((T) JSONObject.parseObject(s, t));
        }
        return list;
    }

    public static <T> List<T> copyList(FindIterable<T> sourceArray) {
        List<T> list = Lists.newArrayList();
        MongoCursor<T> iterator = sourceArray.iterator();
        while (iterator.hasNext()) {
            list.add(iterator.next());
        }
        return list;
    }

    public static Document buildDocument(Class clazz, Boolean... fields) {
        try {
            Document document = new Document();
            Field[] declaredFields = clazz.getDeclaredFields();
            for (int i = 0, length = fields.length; i < length; i++) {
                String name = declaredFields[i].getName();
                // 如果是id 则过滤 id 和 _id
                int type = fields[i] ? 1 : 0;
                if ("id".equals(name)){
                    document.put(MONGO_ID,type );
                }else{
                    document.put(name, type);
                }
            }
            return document;
        } catch (SecurityException e) {
            e.printStackTrace();
        }
        return null;
    }

}
